import React, { useEffect, useState } from 'react';
import ReactDOM from 'react-dom';
/* 
  hook只能用在顶层作用域
  只能用在函数组件

  自定义hook 就是一个以 use 开头的 普通函数  里边可以调用其他hook
  一般在需要抽离某些公用逻辑的时候 会编写自定义hook
  */

function useCount(num = 100) {
  let [n, setN] = useState(num)
  function changeCount(t) {
    setTimeout(() => {
      setN(v => {
        return t == 'add' ? v + 10 : v - 10
      })
    }, 1000);
  }
  useEffect(() => {
    console.log('这是我们定义的副作用：数字更新成功了：' + n)
  })
  return [n, changeCount]
}

function useTimer(n) {
  let [count, setCount] = useState(n)
  let timer = setTimeout(() => {
    setCount((v) => {
      return v - 1
    })
  }, 1000)
  useEffect(() => {
    if (count <= 0) {
      clearTimeout(timer)
    }
  })
  return count
}
function App() {
  // let [count, setCount] = useState(100)
  // if (true) {
  //   [count, setCount] = useState(100)
  // } else {
  //   [count, setCount] = useState(200)
  // }
  let [count, setCount] = useCount(100)
  let n = useTimer(10)
  return <>
    <h2>{count} {n}</h2>
    <button onClick={() => { setCount('add') }}>+</button>
    <button onClick={() => { setCount() }}>-</button>
  </>
}

ReactDOM.render(<App />, document.getElementById('root'))